package org.groovyflow.spring.web;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.springframework.util.StringUtils;

public class Translator {
	//TODO!!!  Get suffix and separator from GroovyFlow ThreadLocal, which is populated
	//in the GroovyFlow filter.  It gets certain things from the applicationContext
	//on init, puts them into a map inside a ThreadLocal, and now we don't have to 
	//inject silly things like suffixes or perhaps even which Translator to use.
	//Less configured singletons.
	private String suffix;
	private String seperator;
	
	public String translate(String ctrlString){
		int index = ctrlString.indexOf("?");
		String params = "";
		if(index > -1){
			params = ctrlString.substring(index);
			ctrlString = ctrlString.substring(0, index);
		}
		StringTokenizer tk = new StringTokenizer( ctrlString, "/");
		List tokens = new ArrayList();
		
		while(tk.hasMoreTokens()){
			tokens.add(tk.nextToken());
		}
		if(tokens.isEmpty()) 
			throw new RuntimeException("No tokens found for " + ctrlString);
		
		StringBuffer buf = new StringBuffer();
		buf.append(tokens.get(0));
		buf.append(seperator);
		if(tokens.size() > 1)
			buf.append(tokens.get(1));
		if(getSuffix() != null)
			buf.append(getSuffix());
		buf.append(params);
		return buf.toString();
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public String getSeperator() {
		return seperator;
	}

	public void setSeperator(String seperator) {
		this.seperator = seperator;
	}
	
	public static void main(String[] args){
		Translator t = new Translator();
		t.setSeperator("_");
		t.setSuffix(".do");
		String input = "ctrl/try";
		System.out.println(t.translate(input));
		input = "ctrl";
		System.out.println(t.translate(input));
		input = "ctrl/";
		System.out.println(t.translate(input));
		
		input = "ctrl/meth?param1=1&param2=2";
		System.out.println(t.translate(input));	

		input = "ctrl?param1=1&param2=2";
		System.out.println(t.translate(input));
		
	}
	

}
